package cn.sumpu.app.guoguojie.web.mvc.misc;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.sumpu.app.guoguojie.biz.AppconfBiz;
import cn.sumpu.app.guoguojie.biz.DoingBiz;
import cn.sumpu.app.guoguojie.biz.IdentifierBiz;
import cn.sumpu.app.guoguojie.biz.ImageBiz;
import cn.sumpu.app.guoguojie.biz.TopBiz;
import cn.sumpu.app.guoguojie.biz.TopShopBiz;
import cn.sumpu.app.guoguojie.biz.impl.top.ConnectionListener;
import cn.sumpu.app.guoguojie.biz.impl.top.MessageListener;
import cn.sumpu.app.guoguojie.constant.DoingProductFrom;
import cn.sumpu.app.guoguojie.domain.DoingProduct;
import cn.sumpu.app.guoguojie.domain.TaobaokeShop;
import cn.sumpu.app.guoguojie.exception.AppBusinessException;
import cn.sumpu.app.guoguojie.util.Common;
import cn.sumpu.app.guoguojie.util.ImageWeb;
import cn.sumpu.app.guoguojie.util.ProductBs;
import cn.sumpu.app.guoguojie.util.PageModel;

import com.taobao.api.*;
import com.taobao.api.domain.*;
import com.taobao.api.internal.stream.*;
import com.taobao.api.request.*;
import com.taobao.api.response.*;

@Controller
public class TopController {

    private final static Logger logger          = LoggerFactory.getLogger(TopController.class);

    private Set<String>         connectedAppkey = new HashSet<String>();

    @Autowired
    private TopBiz              topBiz;
    @Autowired
    private MessageListener     messageListener;
    @Autowired
    private ConnectionListener  connectionListener;
    @Autowired
    private DoingBiz            doingBiz;
    @Autowired
    private TopShopBiz          topShopBiz;
    @Autowired
    private ImageBiz            imageBiz;
    @Autowired
    private IdentifierBiz       idBiz;
    @Autowired
    private AppconfBiz          appconfBiz;

    @RequestMapping(value = "/misc/top/product.htm")
    public String product(HttpServletRequest request, HttpServletResponse response) {
        return "misc/top/product";
    }

    @RequestMapping(value = "/misc/top/getcats.htm")
    public String getCats(Long cid, HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("text/html; charset=UTF-8");
        PrintWriter pw = null;
        try {
            if (null == cid) {
                cid = 0L;
            }
            TaobaoClient client = new DefaultTaobaoClient(topBiz.getUrl(), topBiz.getAppkey(), topBiz.getAppsecret());
            ItemcatsGetRequest req = new ItemcatsGetRequest();
            req.setFields("cid,parent_cid,name,is_parent");
            req.setParentCid(cid);
            ItemcatsGetResponse catsResp = client.execute(req);
            pw = response.getWriter();
            pw.print(JSONObject.fromObject(catsResp));
        } catch (Exception e) {
            try {
                pw = response.getWriter();
                pw.print("error");
            } catch (IOException e1) {
                // ignore
            }
            if (logger.isErrorEnabled()) {
                logger.error("[/misc/top/getcats.htm] fail", e);
            }
        }
        return null;
    }

    @RequestMapping(value = "/misc/top/getproduct.htm")
    public String taobaoitems(Long cid, String autoSend, String startPrice, String endPrice, String area, String startCredit, String endCredit, String sort,
                              String guarantee, String startCommissionRate, String endCommissionRate, String startCommissionNum, String endCommissionNum,
                              String startTotalnum, String endTotalnum, String cashCoupon, String vipCard, String overseasItem, String sevendaysReturn,
                              String realDescribe, String onemonthRepair, String cashOndelivery, String mallItem, Long page, Long pagesize,
                              HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("text/html; charset=UTF-8");
        PrintWriter pw = null;
        try {
            if (null == cid) {
                cid = 0L;
            }
            TaobaoClient client = new DefaultTaobaoClient(topBiz.getUrl(), topBiz.getAppkey(), topBiz.getAppsecret());
            TaobaokeItemsGetRequest req = new TaobaokeItemsGetRequest();
            req.setFields("num_iid,title,nick,pic_url,price,click_url,commission,commission_rate,commission_num,commission_volume,shop_click_url,seller_credit_score,item_location,volume");
            req.setPid(Long.parseLong(topBiz.getPid()));
            req.setCid(cid);
            //          价格
            if (!Common.empty(startPrice) && !Common.empty(endPrice)) {
                req.setStartPrice(startPrice);//开始价格
                req.setEndPrice(endPrice);//最高价格
            }
            req.setAutoSend(autoSend);
            //          商品所在地
            req.setArea(area);
            //卖家信用
            if (!Common.empty(startCredit) && !Common.empty(endCredit)) {
                req.setStartCredit(startCredit);//卖家信用开始
                req.setEndCredit(endCredit);//卖家信用结束
            }

            //默认排序:default price_desc(价格从高到低) price_asc(价格从低到高) 
            //credit_desc(信用等级从高到低) commissionRate_desc(佣金比率从高到低) commissionRate_asc(佣金比率从低到高) 
            //commissionNum_desc(成交量成高到低) commissionNum_asc(成交量从低到高) commissionVolume_desc(总支出佣金从高到低)
            //commissionVolume_asc(总支出佣金从低到高) delistTime_desc(商品下架时间从高到低) delistTime_asc(商品下架时间从低到高)
            req.setSort(sort);
            //          是否查询消保卖家
            req.setGuarantee(guarantee);
            //佣金比例
            if (!Common.empty(startCommissionRate) && !Common.empty(endCommissionRate)) {
                req.setStartCommissionRate(String.valueOf((int) Double.parseDouble(startCommissionRate) * 100));//佣金比率下限
                req.setEndCommissionRate(String.valueOf((int) Double.parseDouble(endCommissionRate) * 100));//佣金比率上限
            }
            //30天累计推广量
            if (!Common.empty(startCommissionNum) && !Common.empty(endCommissionNum)) {
                req.setStartCommissionNum(startCommissionNum);//下限
                req.setEndCommissionNum(endCommissionNum);//上限
            }
            //商品总成交量
            if (!Common.empty(startTotalnum) && !Common.empty(endTotalnum)) {
                req.setStartTotalnum(startTotalnum);//下限
                req.setEndTotalnum(endTotalnum);//上限
            }

            req.setCashCoupon(cashCoupon);//是否支持抵价券，设置为true表示该商品支持抵价券，设置为false或不设置表示不判断这个属性
            req.setVipCard(vipCard);//是否支持VIP卡，设置为true表示该商品支持VIP卡，设置为false或不设置表示不判断这个属性
            req.setOverseasItem(overseasItem);//是否海外商品，设置为true表示该商品是属于海外商品，默认为false
            req.setSevendaysReturn(sevendaysReturn);//是否海外商品，设置为true表示该商品是属于海外商品，默认为false
            req.setRealDescribe(realDescribe);//是否如实描述(即:先行赔付)商品，设置为true表示该商品是如实描述的商品，设置为false或不设置表示不判断这个属性
            req.setOnemonthRepair(onemonthRepair);//是否30天维修，设置为true表示该商品是支持30天维修，设置为false或不设置表示不判断这个属性
            req.setCashOndelivery(cashOndelivery);//是否支持货到付款，设置为true表示该商品是支持货到付款，设置为false或不设置表示不判断这个属性
            req.setMallItem(mallItem);//是否商城的商品，设置为true表示该商品是属于淘宝商城的商品，设置为false或不设置表示不判断这个属性
            if (page == null)
                page = 1L;
            req.setPageNo(page);
            if (pagesize == null)
                pagesize = 20L;
            req.setPageSize(pagesize);

            TaobaokeItemsGetResponse itemsResp = client.execute(req);
            doingBiz.getProductsContain(DoingProductFrom.TAOBAO.getValue(), itemsResp.getTaobaokeItems());

            pw = response.getWriter();
            pw.print(JSONObject.fromObject(itemsResp));
        } catch (Exception e) {
            try {
                pw = response.getWriter();
                pw.print("error");
            } catch (IOException e1) {
                // ignore
            }
            if (logger.isErrorEnabled()) {
                logger.error("[/misc/top/getproduct.htm] fail", e);
            }
        }
        return null;
    }

    @RequestMapping(value = "/misc/top/report.htm")
    public String report(HttpServletRequest request, HttpServletResponse response) {
        return "misc/top/report";
    }

    @RequestMapping(value = "/misc/top/getreport.htm")
    public String getReport(String date, Long pageNo, Long pagesize, HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("text/html; charset=UTF-8");
        PrintWriter pw = null;
        try {
            pw = response.getWriter();
            String sessionkey = appconfBiz.getTopSession();//FIXME 临时解决方案
            TaobaokeReport r = topBiz.getReport(date, pagesize, pageNo, sessionkey);
            pw.print(JSONObject.fromObject(r));
        } catch (Exception e) {
            pw.print("error");
            if (logger.isErrorEnabled()) {
                logger.error("[/misc/top/getreport.htm] fail", e);
            }
        }
        return null;
    }

    @RequestMapping(value = "/misc/top/comet.htm")
    public synchronized String comet(HttpServletRequest request, HttpServletResponse response) {
        return "misc/top/comet";
    }

    @RequestMapping(value = "/misc/top/startcomet.htm")
    public synchronized String startComet(HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setContentType("text/html; charset=UTF-8");
            if (connectedAppkey.contains(topBiz.getAppkey())) {
                response.getWriter().write("<center><font color=\"red\">重复的连接，此次连接将被丢弃掉，不发起对comet的真正连接请求</font></center>");
                return null;
            }
            Configuration config = new Configuration(topBiz.getAppkey(), topBiz.getAppsecret(), null);
            TopCometStream stream = new TopCometStreamFactory(config).getInstance();
            stream.setConnectionListener(connectionListener);
            stream.setMessageListener(messageListener);
            stream.start();
            connectedAppkey.add(topBiz.getAppkey());
            response.getWriter().write("<center><font color=\"green\">comet服务启动成功</font></center>");
        } catch (Exception e) {
            if (logger.isErrorEnabled()) {
                logger.error("[/misc/top/startcomet.htm] fail", e);
            }
        }
        return null;
    }

    @RequestMapping(value = "/misc/top/toshareproduct.htm")
    public String toshareproduct(String id, HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setContentType("text/html; charset=UTF-8");
            DoingProduct dp = doingBiz.getProductContain(DoingProductFrom.TAOBAO.getValue(), id);
            if (dp != null) {
                response.getWriter().print("same");
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "misc/top/shareproduct";
    }

    //通过淘宝商品id取得淘宝商品
    @RequestMapping(value = "/misc/top/getproductinfo.htm")
    public String getproductinfo(String id, HttpServletRequest request, HttpServletResponse response) {
        PrintWriter out = null;
        try {
            response.setContentType("text/html; charset=UTF-8");
            out = response.getWriter();
            ProductBs productBs = topBiz.convertTaobao(id);
            out.print(JSONObject.fromObject(productBs));
        } catch (Exception e) {
            e.printStackTrace();
            out.print("{\"error\":\"error\"}");
        }
        return null;
    }

    @RequestMapping(value = "/misc/top/topshop.htm")
    public String topShop() {
        return "misc/top/topShop/topShop";
    }

    @RequestMapping(value = "/misc/top/topshopgrid.htm")
    public String topShopGrid(Integer page, Integer pagesize, String shopName, HttpServletResponse response) {
        response.setContentType("text/html; charset=UTF-8");
        PrintWriter pw = null;
        try {
            PageModel pageModel = topShopBiz.getTopShop(page, pagesize, 0, shopName);
            pw = response.getWriter();
            pw.print(JSONObject.fromObject(pageModel));
        } catch (Exception e) {
            if (logger.isErrorEnabled()) {
                logger.error("[/misc/top/topshop.htm] fail", e);
            }
        }
        return null;
    }

    @RequestMapping(value = "/misc/top/addtopshop.htm")
    public String addTopShop(HttpServletRequest request) {
        try {
            String id = idBiz.generateId("taobaoke_shop");
            request.setAttribute("identifier", id);
            request.setAttribute("saveType", "add");
        } catch (AppBusinessException e) {
            logger.error("[/misc/top/addtopshop.htm] fail", e);
        }
        return "misc/top/topShop/saveTopShop";
    }

    @RequestMapping(value = "/misc/top/edittopshop.htm")
    public String editTopShop(HttpServletRequest request, String id) {
        try {
            TaobaokeShop taobaokeShop = topShopBiz.getTopShopById(id);
            request.setAttribute("taobaokeShop", taobaokeShop);
            request.setAttribute("identifier", id);
            request.setAttribute("saveType", "edit");
        } catch (AppBusinessException e) {
            logger.error("[/misc/top/edittopshop.htm] fail", e);
        }
        return "misc/top/topShop/saveTopShop";
    }

    @RequestMapping(value = "/misc/top/savetopshop.htm")
    public String saveTopShop(HttpServletResponse response, TaobaokeShop taobaokeShop, String saveType) {
        try {
            response.setContentType("text/html; charset=UTF-8");
            PrintWriter pw = response.getWriter();
            topShopBiz.saveTopShop(taobaokeShop, saveType);
            pw.print("success");
        } catch (Exception e) {
            if (logger.isErrorEnabled()) {
                logger.error("[/misc/top/savetopshop.htm] fail", e);
            }
        }
        return null;
    }

    @RequestMapping(value = "/misc/top/torebate.htm")
    public String torebate(HttpServletRequest request, HttpServletResponse response) {
        try {
            request.setAttribute("guoguojieCommissionMin", appconfBiz.getGuoguojieCommissionMin());
            request.setAttribute("guoguojieCommissionRate", appconfBiz.getGuoguojieCommissionRate());
        } catch (Exception e) {
            if (logger.isErrorEnabled()) {
                logger.error("[/misc/top/torebate.htm] fail", e);
            }
        }
        return "misc/top/rebate";
    }

    @RequestMapping(value = "/misc/top/rebate.htm")
    public String rebate(String guoguojieCommissionRate, String guoguojieCommissionMin, HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("text/html; charset=UTF-8");
        PrintWriter pw = null;
        try {
            pw = response.getWriter();
            appconfBiz.setGuoguojieCommissionMin(guoguojieCommissionMin);
            appconfBiz.setGuoguojieCommissionRate(guoguojieCommissionRate);
            pw.print("success");
        } catch (Exception e) {
            try {
                pw = response.getWriter();
                pw.print("error");
            } catch (IOException e1) {
                // ignore
            }
            if (logger.isErrorEnabled()) {
                logger.error("[/misc/top/rebate.htm] fail", e);
            }
        }
        return null;
    }

    @RequestMapping(value = "/misc/top/deletetopshop.htm")
    public String deleteTopShop(HttpServletResponse response, String id) {
        try {
            response.setContentType("text/html; charset=UTF-8");
            PrintWriter pw = response.getWriter();
            TaobaokeShop taobaokeShop = topShopBiz.getTopShopById(id);
            if (!Common.empty(taobaokeShop)) {
                String url = taobaokeShop.getLogo();
                if (!Common.empty(url)) {
                    int index = url.indexOf("pic");
                    int lastIndex = url.lastIndexOf("pic");
                    String imageServer = "";
                    String imageFile = "";
                    if (index > 0 && lastIndex > 0) {
                        imageServer = url.substring(0, index);
                        imageFile = url.substring(lastIndex);
                        imageBiz.requestDeleteImage(imageServer + "deleteImage.htm", imageFile);
                    }

                }
            }
            topShopBiz.deleteTopShopById(id);
            pw.print("success");
        } catch (Exception e) {
            if (logger.isErrorEnabled()) {
                logger.error("[/misc/top/deletetopshop.htm] fail", e);
            }
        }
        return null;
    }

    //上传店铺logo
    @RequestMapping(value = "/misc/top/uploadlogo.htm")
    public String uploadLogo(HttpServletRequest request, HttpServletResponse response, String identifier) {
        response.setContentType("text/html; charset=UTF-8");
        PrintWriter pw = null;
        try {
            String fileName = "";
            String fileType = "";
            if (!Common.empty(identifier)) {
                fileType = "topShop";
                fileName = identifier;
            }
            if (Common.empty(identifier)) {
                fileType = "topShop/tmp";
                fileName = Common.getFormatDate(new Date()) + UUID.randomUUID().toString();
            }
            request.setAttribute("fileType", fileType);
            request.setAttribute("fileName", fileName);
            ImageWeb imageWeb = imageBiz.uploadOneImg(request);
            pw = response.getWriter();
            pw.println(JSONObject.fromObject(imageWeb).toString());
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("[/member/avatarup.htm] fail", e);
        }
        return null;
    }

    @RequestMapping(value = "/misc/top/obtaintr.htm")
    public String obtainTaobaokeReport(String obtainDate, HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("text/html; charset=UTF-8");
        PrintWriter pw = null;
        try {
            String sessionkey = appconfBiz.getTopSession();//FIXME 临时解决方案
            topBiz.obtainTaobaokeReport(obtainDate, sessionkey);
            pw = response.getWriter();
            pw.print("success");
        } catch (Exception e) {
            try {
                pw = response.getWriter();
                pw.print("error");
            } catch (IOException e1) {
                // ignore
            }
            if (logger.isErrorEnabled()) {
                logger.error("[/misc/top/obtaintr.htm] fail", e);
            }
        }
        return null;
    }
    
    @RequestMapping(value = "/misc/top/taobaokereport.htm")
    public String taobaokeReport(HttpServletRequest request, HttpServletResponse response) {
        return "misc/top/taobaokeReport";
    }
    
    @RequestMapping(value = "/misc/top/gettaobaokereport.htm")
    public String getTaobaokeReport(String page, String pagesize,HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("text/html; charset=UTF-8");
        PrintWriter pw = null;
        try {
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("page", page);
            params.put("pageSize", pagesize);
            PageModel pm = topBiz.getTaobaokeReport(params);
            pw = response.getWriter();
            pw.print(JSONObject.fromObject(pm));
        } catch (Exception e) {
            if (logger.isErrorEnabled()) {
                logger.error("[/misc/top/gettaobaokereport.htm] fail", e);
            }
            try {
                pw = response.getWriter();
                pw.print("error");
            } catch (IOException e1) {
                // ignore
            }
        }
        return null;
    }
}
